#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0   # offline image build: defer to first boot
_cored=/usr/bin/relayway-cored
_backup=/usr/bin/relayway-cored.pre-upgrade
_version=/usr/share/relayway-cored/VERSION
_version_backup=/usr/share/relayway-cored/VERSION.pre-upgrade
_version_missing=/usr/share/relayway-cored/VERSION.pre-upgrade.missing
_www=/usr/share/relayway-cored/www
_www_backup=/usr/share/relayway-cored/www.pre-upgrade
_www_missing=/usr/share/relayway-cored/www.pre-upgrade.missing
_p="$(uci -q get relayway.cored.port 2>/dev/null)"; [ -n "$_p" ] || _p=7654
_l="$(uci -q get relayway.cored.listen 2>/dev/null)"; [ -n "$_l" ] || _l=0.0.0.0
case "$_l" in ""|0.0.0.0) _h=127.0.0.1 ;; ::|'[::]') _h='[::1]' ;; *) _h="$_l" ;; esac

relayway_start_cored() {
    /etc/init.d/relayway-cored restart 2>/dev/null || \
        /etc/init.d/relayway-cored start 2>/dev/null
}

relayway_cored_healthy() {
    _i=0; _stable=0
    while [ "$_i" -lt 30 ]; do
        if /etc/init.d/relayway-cored running >/dev/null 2>&1 && {
            { command -v curl >/dev/null 2>&1 && curl -fsS --connect-timeout 2 --max-time 3 "http://$_h:$_p/api/v1/health" -o /dev/null; } ||
            { command -v wget >/dev/null 2>&1 && wget -T 3 -qO /dev/null "http://$_h:$_p/api/v1/health"; } ||
            { command -v uclient-fetch >/dev/null 2>&1 && uclient-fetch -T 3 -qO /dev/null "http://$_h:$_p/api/v1/health"; }
        }; then
            _stable=$((_stable + 1)); [ "$_stable" -lt 3 ] || return 0
        else
            _stable=0
        fi
        _i=$((_i + 1)); sleep 1
    done
    return 1
}

relayway_verify_version() {
    _expected="$(tr -d '\r\n' < "$_version" 2>/dev/null)"
    _actual="$($_cored --version 2>/dev/null | sed -n '1{s/^[[:space:]]*//;s/[[:space:]]*$//;p;q;}')"
    [ -n "$_expected" ] && {
        [ "$_actual" = "$_expected" ] || [ "$_actual" = "relayway-cored $_expected" ]
    }
}

relayway_restore_previous_web() {
    if [ -d "$_www_backup" ] && [ ! -L "$_www_backup" ]; then
        if [ -e "$_www" ] || [ -L "$_www" ]; then rm -rf "$_www"; fi
        mv "$_www_backup" "$_www" || {
            echo "relayway: previous Web directory could not be restored; backup retained at $_www_backup" >&2
            return 1
        }
    elif [ -f "$_www_missing" ]; then
        if [ -e "$_www" ] || [ -L "$_www" ]; then rm -rf "$_www"; fi
    else
        echo "relayway: no usable previous Web directory backup is available" >&2
        return 1
    fi
    return 0
}

relayway_restore_previous_cored() {
    _reason="$1"
    _restore_tmp="${_cored}.restore.$$"
    echo "$_reason; attempting to restore the previous cored binary" >&2
    [ -f "$_backup" ] && [ -x "$_backup" ] || {
        echo "relayway: no usable previous cored binary is available at $_backup" >&2
        return 1
    }
    rm -f "$_restore_tmp"
    if ! cp -p "$_backup" "$_restore_tmp" || \
       ! chmod 0755 "$_restore_tmp" || \
       ! mv -f "$_restore_tmp" "$_cored"; then
        rm -f "$_restore_tmp"
        echo "relayway: failed to put the previous cored binary back; backup retained at $_backup" >&2
        return 1
    fi
    if [ -f "$_version_backup" ]; then
        _version_restore_tmp="${_version}.restore.$$"
        if ! cp -p "$_version_backup" "$_version_restore_tmp" || \
           ! chmod 0644 "$_version_restore_tmp" || \
           ! mv -f "$_version_restore_tmp" "$_version"; then
            rm -f "$_version_restore_tmp"
            echo "relayway: previous VERSION marker could not be restored; backup retained at $_version_backup" >&2
            return 1
        fi
    elif [ -f "$_version_missing" ]; then
        if [ -e "$_version" ] || [ -L "$_version" ]; then rm -f "$_version" || return 1; fi
    elif [ -e "$_version" ] || [ -L "$_version" ]; then
        # An older maintainer script may not have recorded the absence of
        # VERSION. Never leave the new marker attached to the old binary.
        rm -f "$_version" || return 1
    fi
    relayway_restore_previous_web || return 1
    if ! relayway_start_cored; then
        echo "relayway: previous cored binary was restored on disk but could not be started; backup retained at $_backup" >&2
        return 1
    fi
    if ! relayway_cored_healthy; then
        echo "relayway: previous cored binary was restored on disk but failed the health gate; backup retained at $_backup" >&2
        return 1
    fi
    echo "relayway: previous cored binary restored and healthy; failed upgrade remains reported" >&2
    return 0
}

relayway_fail_install() {
    _reason="$1"
    if ! relayway_restore_previous_cored "$_reason"; then
        echo "relayway: automatic rollback failed; restore $_backup to $_cored and restart relayway-cored manually" >&2
    fi
    exit 1
}

/etc/init.d/relayway-cored enable 2>/dev/null || {
    relayway_fail_install "relayway: failed to enable relayway-cored"
}
# `restart` (NOT `start`): on an OVER-INSTALL the old cored may still be running and
# procd's `start` is a NO-OP (it diffs the declarative instance config — command +
# args + env — not the binary content on disk), so the freshly-unpacked binary
# would never actually run; the box keeps executing the OLD version. restart
# re-execs it. The preinst intentionally leaves the old service online until
# unpack completes; the fallback covers boxes where restart is unavailable.
# (Parity with install.sh step 6, line 318.)
if ! relayway_start_cored; then
    relayway_fail_install "relayway: failed to start relayway-cored after install"
fi
relayway_cored_healthy || relayway_fail_install "relayway: cored failed its post-install health gate"
relayway_verify_version || relayway_fail_install "relayway: cored version does not match installed VERSION marker"
rm -f "$_backup" "$_version_backup" "$_version_missing" "$_www_missing" || {
    echo "relayway: new cored is healthy but its rollback artifact could not be removed: $_backup" >&2
    exit 1
}
rm -rf "$_www_backup" || {
    echo "relayway: new cored is healthy but its Web rollback artifact could not be removed: $_www_backup" >&2
    exit 1
}
# Tell the operator where the admin dashboard is (parity with install.sh step 7).
_ip="$(uci -q get network.lan.ipaddr 2>/dev/null)"
[ -n "$_ip" ] || _ip="$(ip -4 route get 1 2>/dev/null | sed -n 's/.*src \([0-9.]*\).*/\1/p' | head -1)"
[ -n "$_ip" ] || _ip="<router-lan-ip>"
_ip="${_ip%%/*}"
echo "relayway: admin dashboard -> http://$_ip:$_p/"
echo "relayway: (standalone engine, optional) edit /etc/relayway/config.json then /etc/init.d/relayway enable && start"
exit 0
